package com.mmren.edu.dtx.service;

import com.mmren.edu.dtx.domain.Stock;
import com.mmren.edu.dtx.mapper.StockMapper;
import com.mmren.edu.dtx.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 欢迎来到牧码人教育，做Java我们是专业的
 *
 * @创建人： 牧码人教育-Gerry
 * @创建时间： 2020-4-20
 * @功能描述：
 */
@Service
public class StockServiceImpl implements StockService {

    @Autowired
    private StockMapper stockMapper;

    @Transactional
    @Override
    public boolean reduceStock(OrderVO vo) {
        // 获取商品库存信息
        Stock stock = stockMapper.getStockByProductId(vo.getProductId());
        if (stock==null) {
            throw new RuntimeException("商品不存在对应库存信息");
        }
        // 判断库存是否充足
        if (stock.getAmount() - vo.getAmount() < 0) {
            throw new RuntimeException("商品库存不足.");
        }
        // 扣减库存
        int flag = stockMapper.updateStock(vo);

        if (vo.getAmount() == 20) {
            throw new RuntimeException("库存操作出现异常,测试事务是否出现回滚");
        }

        return flag > 0;
    }
}
